<template>
  <div class="missing-container">
    <!-- 顶部操作栏 -->
    <div class="header-section">
      <div class="search-section">
        <el-input
          v-model="searchText"
          placeholder="请输入姓名/家属姓名搜索"
          class="search-input"
          clearable
        >
          <template #prepend>
            <el-select v-model="searchType" placeholder="类型" style="width: 110px">
              <el-option label="姓名搜索" value="name" />
              <el-option label="家属搜索" value="relative" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" type="danger" @click="handleSearch" />
          </template>
        </el-input>
      </div>

      <div class="action-section">
        <div class="filter-group">
          <el-dropdown split-button type="danger">
            筛选
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="filterByStatus(0)">
                  <el-tag type="info">未找到</el-tag>
                </el-dropdown-item>
                <el-dropdown-item @click="filterByStatus(1)">
                  <el-tag type="success">已找到</el-tag>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button type="danger" @click="handlePublish">
            <el-icon><Plus /></el-icon>发布寻人
          </el-button>
        </div>
      </div>
    </div>

    <!-- 数据统计 -->
    <div class="stats-box">
      <el-statistic title="总登记数" :value="totalCount" class="stat-item" />
      <el-statistic title="已找到" :value="foundCount" class="stat-item">
        <template #suffix>
          <el-tag type="success" size="small">人</el-tag>
        </template>
      </el-statistic>
      <el-statistic title="未找到" :value="totalCount - foundCount" class="stat-item">
        <template #suffix>
          <el-tag type="danger" size="small">人</el-tag>
        </template>
      </el-statistic>
    </div>

    <!-- 人员卡片列表 -->
    <div class="card-list">
      <el-row :gutter="16">
        <el-col
          v-for="item in paginatedData"
          :key="item.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="4"
        >
          <el-card
            class="person-card"
            :body-style="{ padding: '12px' }"
            shadow="hover"
            @click="showDetail(item)"
          >
            <div class="card-header">
              <el-tag :type="item.status ? 'success' : 'danger'" size="small" effect="dark">
                {{ item.status ? "已找到" : "寻找中" }}
              </el-tag>
              <span class="missing-date">{{ item.missingDate }}</span>
            </div>

            <div class="person-image-wrapper">
              <img class="person-image" :src="item.photos[0]" @error="handleImageError" />
            </div>

            <div class="person-info">
              <h3 class="person-name">{{ item.name }}</h3>
              <div class="meta-info">
                <span>{{ item.gender }}</span>
                <el-divider direction="vertical" />
                <span>{{ item.age }}岁</span>
                <el-divider direction="vertical" />
                <span class="location">{{ item.missingLocation }}</span>
              </div>
            </div>

            <!-- 底部操作栏 -->
            <div class="card-footer">
              <div class="action-buttons">
                <el-tooltip content="收藏" placement="bottom">
                  <el-icon
                    class="collect-btn"
                    :class="{ collected: item.isCollected }"
                    @click.stop="toggleCollect(item)"
                  >
                    <StarFilled />
                  </el-icon>
                </el-tooltip>

                <el-divider direction="vertical" />

                <el-dropdown trigger="click" @click.stop>
                  <el-tooltip content="分享" placement="top">
                    <el-icon class="share-btn">
                      <Share />
                    </el-icon>
                  </el-tooltip>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="sharePerson(item, 'wechat')">
                        <el-icon class="wechat-icon"><ChatDotRound /></el-icon>微信
                      </el-dropdown-item>
                      <el-dropdown-item @click="sharePerson(item, 'link')">
                        <el-icon class="link-icon"><Link /></el-icon>复制链接
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[8, 16, 24, 32]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredData.length"
        background
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" :title="currentDetail?.name + ' 的详细信息'" width="60%">
      <div v-if="currentDetail" class="detail-content">
        <img class="detail-image" :src="currentDetail.photos[0]" @error="handleImageError" />
        <div class="detail-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="姓名">{{ currentDetail.name }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ currentDetail.gender }}</el-descriptions-item>
            <el-descriptions-item label="年龄">{{ currentDetail.age }}</el-descriptions-item>
            <el-descriptions-item label="失踪日期">{{ currentDetail.missingDate }}</el-descriptions-item>
            <el-descriptions-item label="失踪地点">{{ currentDetail.missingLocation }}</el-descriptions-item>
            <el-descriptions-item label="特征描述">{{ currentDetail.description }}</el-descriptions-item>
            <el-descriptions-item label="家属联系方式">
              <el-link type="danger" :href="`tel:${currentDetail.contact}`">
                {{ currentDetail.contact }}
              </el-link>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  Search, Plus, StarFilled, Share, ChatDotRound, Link
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

interface IMissingPerson {
  id: number
  name: string
  gender: string
  age: number
  missingDate: string
  missingLocation: string
  description: string
  contact: string
  photos: string[]
  status: number
  isCollected: boolean
}

const mockData: IMissingPerson[] = [
  {
    id: 1,
    name: '王小明的测试数据',
    gender: '男',
    age: 12,
    missingDate: '2023-05-01',
    missingLocation: '北京市朝阳区公园',
    description: '身高140cm，失踪时穿蓝色校服，戴红色帽子',
    contact: '138-1234-5678',
    photos: ['https://dummyimage.com/300x400/ff0000/ffffff'],
    status: 0,
    isCollected: false
  },
  {
    id: 2,
    name: '李小红',
    gender: '女',
    age: 8,
    missingDate: '2023-06-15',
    missingLocation: '上海市南京路步行街',
    description: '扎双马尾，门牙缺失，右臂有胎记',
    contact: '139-8765-4321',
    photos: [],
    status: 1,
    isCollected: true
  }
]

const searchText = ref('')
const searchType = ref('name')
const currentPage = ref(1)
const pageSize = ref(8)
const detailVisible = ref(false)
const currentDetail = ref<IMissingPerson | null>(null)
const allData = ref<IMissingPerson[]>([])

// 计算属性
const totalCount = computed(() => allData.value.length)
const foundCount = computed(() => allData.value.filter(item => item.status === 1).length)

const filteredData = computed(() => {
  return allData.value.filter(item => {
    const searchLower = searchText.value.toLowerCase()
    const nameMatch = item.name.toLowerCase().includes(searchLower)
    const relativeMatch = item.contact.includes(searchText.value)

    if (searchType.value === 'name') return nameMatch
    if (searchType.value === 'relative') return relativeMatch
    return nameMatch || relativeMatch
  })
})

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

// 方法
const showDetail = (item: IMissingPerson) => {
  currentDetail.value = item
  detailVisible.value = true
}

const filterByStatus = (status: number) => {
  allData.value = mockData.filter(item => item.status === status)
}

const handleSearch = () => {
  currentPage.value = 1
}

const handlePublish = () => {
  router.push('/publish-search/create-notice')
}

const toggleCollect = (item: IMissingPerson) => {
  item.isCollected = !item.isCollected
  ElMessage.success(item.isCollected ? '已收藏' : '已取消收藏')
}

const sharePerson = (item: IMissingPerson, type: string) => {
  const shareLink = `${location.origin}/detail/${item.id}`
  if (type === 'link') {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(shareLink)
        .then(() => {
          ElMessage.success('链接已复制到剪贴板')
        })
        .catch(() => {
          const textArea = document.createElement('textarea')
          textArea.value = shareLink
          document.body.appendChild(textArea)
          textArea.select()
          document.execCommand('copy')
          document.body.removeChild(textArea)
          ElMessage.success('链接已复制到剪贴板')
        })
    } else {
      const textArea = document.createElement('textarea')
      textArea.value = shareLink
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      ElMessage.success('链接已复制到剪贴板')
    }
  } else {
    ElMessage.info('请使用手机进行分享')
  }
}

const handleImageError = (e: Event) => {
  const img = e.target as HTMLImageElement
  img.src = ''
  img.alt = '暂无照片'
  img.style.backgroundColor = '#f5f5f5'
}

onMounted(() => {
  allData.value = mockData
})
</script>

<style scoped lang="scss">
.missing-container {
  padding: 10px;
  width: 100%;
  margin: 0 auto;

  .header-section {
    display: flex;
    gap: 20px;
    margin-bottom: 10px;

    .search-section {
      flex: 1;

      :deep(.el-input__wrapper){
        background-color: var(--detail-section-background);
      }
      :deep(.el-input){
        --el-color-primary: #ff4e4f;
      }

      :deep(.el-input-group__prepend) {
        background-color: #ff4e4f;
      }
      :deep(.el-select__placeholder) {
        color: white;
      }
      :deep(.el-select__suffix) {
        color: white;
      }
      :deep(.el-input-group__append, .el-input-group__prepend) {
        background: #ff414d;
        color: white;
      }

    }

    .action-section {
      .filter-group {
        display: flex;
        gap: 12px;

        .el-button {
          padding: 8px 16px;

          .el-icon {
            margin-right: 6px;
          }
        }
      }
    }
  }

  .stats-box {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 24px;
    margin-bottom: 5px;
    padding: 16px;
    border: 1px solid;
    border-radius: 8px;

    .stat-item {
      text-align: center;

      :deep(.el-statistic__head) {
        margin-bottom: 8px;
        font-size: 14px;
      }

      :deep(.el-statistic__number) {
        font-size: 24px;
        font-weight: 600;
      }
    }
  }

  .person-card {
    transition: transform 0.2s ease, box-shadow 0.2s ease;
    cursor: pointer;

    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .missing-date {
        font-size: 12px;
      }
    }

    .person-image-wrapper {
      position: relative;
      width: 100%;
      padding-top: 100%;
      border-radius: 4px;
      overflow: hidden;

      .person-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .person-info {
      padding: 12px 0 4px;

      .person-name {
        margin: 0 0 8px;
        font-size: 16px;
        text-align: center;
      }

      .meta-info {
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 12px;

        .location {
          max-width: 120px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    .card-footer {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px solid;

      .action-buttons {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 12px;

        .el-icon {
          font-size: 32px;
          padding: 6px;
          border-radius: 50%;
          cursor: pointer;
          transition: all 0.2s;

          &:hover {
            background: #ff7875;
          }
        }

        .collect-btn {
          &.collected {
            color: #ff6b6b;
          }
        }

        .share-btn {
          color: #666;
        }
      }
    }
  }

  .pagination-wrapper {
    margin-top: 10px;
    display: flex;
    justify-content: center;
  }

  .detail-content {
    display: grid;
    grid-template-columns: 200px 1fr;
    gap: 24px;

    .detail-image {
      width: 100%;
      height: 250px;
      object-fit: cover;
      border-radius: 4px;
    }
  }
}

:deep(.el-button--danger) {
  background-color: #ff4444;
  border-color: #ff4444;

  &:hover {
    background-color: #ff6666;
    border-color: #ff6666;
  }
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #ff4444;
}
</style>
